package com.glp.work.flow.utils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.apache.commons.collections.MapUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ScriptUtils {
	
	private static final String EXPRESS_LANGUAGE = "js";
	private static final ScriptEngineManager SCRIPT_ENGINE_MANAGER = new ScriptEngineManager();
	private static final ScriptEngine SCRIPT_ENGINE;

	public static Object eval(String express, Map<String, Object> parameter) {
		if (express == null) {
			return null;
		} else {
			try {
				if (!MapUtils.isEmpty(parameter)) {
					Iterator e = parameter.entrySet().iterator();

					while (e.hasNext()) {
						Entry entry = (Entry) e.next();
						SCRIPT_ENGINE.put((String) entry.getKey(), entry.getValue());
					}
				}

				return SCRIPT_ENGINE.eval(express);
			} catch (Exception arg3) {
				log.error((String) null, arg3);
				return null;
			}
		}
	}

	public static boolean equals(String express, Map<String, Object> parameter, Object target) {
		return target == null ? false : target.equals(eval(express, parameter));
	}

	public static boolean isTrue(String express, Map<String, Object> parameter) {
		return equals(express, parameter, Boolean.TRUE);
	}

	public static void main(String[] xxx) {
		HashMap param = new HashMap(1);
		param.put("str", "哈哈test嘿嘿!");
		param.put("a", Integer.valueOf(1));
		param.put("isOK", Boolean.valueOf(true));
		System.out.println(isTrue("true", (Map) null));
		System.out.println(isTrue("str == \"哈哈test嘿嘿!\"", param));
		System.out.println(isTrue("str.equals(\'1test!\') || a==2 && !isOK", param));
	}

	static {
		SCRIPT_ENGINE = SCRIPT_ENGINE_MANAGER.getEngineByName("js");
	}

}
